<?php
function bpt_is_ticket_code_valid( $code ) {
	global $bp, $current_user, $wpdb;

	get_currentuserinfo();
	$purchase_id = 0;

	$matches = $wpdb->get_results( $wpdb->prepare( "select meta_id, meta_value from " . WPSC_TABLE_META . " as meta where object_type = %s and meta_key = %s", 'bp_ticketing', wpsc_sanitize_meta_key( $current_user->user_email ) ) );
	foreach ( (array)$matches as $match ) {
		if ( $match->meta_value == $code ) {
			$purchase_id = $match->meta_id;
			break;
		}
	}

	if ( !$purchase_id )
		return apply_filters( 'bpt_is_ticket_code_valid', false );

	$wpdb->get_results( $wpdb->prepare( "delete from " . WPSC_TABLE_META . " where meta_id = %d limit 1", $purchase_id ) );
	return apply_filters( 'bpt_is_ticket_code_valid', $purchase_id );
}

function bpt_get_ticket_purchases( $user_id=0 ) {
	global $bp, $wpdb;

	if ( !$user_id )
	 	$user_id = $bp->loggedin_user->id;

	$sql = $wpdb->prepare( "select cart.id, cart.prodid as product_id, cart.name as product_name from " . WPSC_TABLE_PURCHASE_LOGS . " as logs, " . WPSC_TABLE_CART_CONTENTS . " as cart,  " . WPSC_TABLE_ITEM_CATEGORY_ASSOC . " as category WHERE logs.id = cart.purchaseid AND cart.prodid = category.product_id AND category.category_id = %d AND logs.user_ID = %d", bpt_get_ticketing_category(), $user_id );
	return apply_filters( 'bpt_get_ticket_purchases', $wpdb->get_results( $sql ), $user_id );
}

function bpt_wpsc_get_product_meta( $product_id, $meta_key ) {
	global $wpdb;

	$sql = $wpdb->prepare( "select meta_value from " . WPSC_TABLE_PRODUCTMETA . " where product_id = %d and meta_key = %s", $product_id, $meta_key );
	return apply_filters( 'bpt_wpsc_get_product_meta', maybe_unserialize( $wpdb->get_var( $sql ) ), $product_id, $meta_key );
}

// This taken from tikipress
function bpt_wpsc_get_categories() {
	global $wpdb;

	$sql = "SELECT `id`, `name` FROM `" . WPSC_TABLE_PRODUCT_CATEGORIES . "` WHERE `active`='1'";
	return apply_filters( 'bpt_wpsc_get_categories', $wpdb->get_results( $sql, ARRAY_A ) );
}

function bpt_get_product_name( $purchase_id ) {
	global $wpdb;

	$sql = $wpdb->prepare( "select cart.name from " . WPSC_TABLE_PURCHASE_LOGS . " as logs, " . WPSC_TABLE_CART_CONTENTS . " as cart WHERE logs.id = cart.purchaseid and logs.id = %d", $purchase_id );
	return apply_filters( 'bpt_get_product_name', $wpdb->get_var( $sql ), $purchase_id );
}
?>